﻿using System;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using System.Linq;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Collections.Generic;
using System.Web.UI;
using System.Xml;

namespace Dunite.InfoRoad
{
    [ToolboxItemAttribute(false)]
    public partial class XmlFormView : WebPart
    {
        // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution
        // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
        // for production. Because the SecurityPermission attribute bypasses the security check for callers of
        // your constructor, it's not recommended for production purposes.
        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        public XmlFormView()
        {
        }

        public InfoRoadFile infoRoadFile;
        public string ViewName;
        protected TextBox otherJSON;
        protected List<Literal> htmlLabels;
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            //foreach (Literal label in htmlLabels)
            //{

            //}
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string fileName = HttpContext.Current.Request["FileLocation"];
            string templatePath = HttpContext.Current.Request["FormTemplate"];
            string SaveLocation = HttpContext.Current.Request["SaveLocation"];

            if (this.Page.IsPostBack)
            {
                this.infoRoadFile = new InfoRoadFile();
                this.infoRoadFile.ReadJson(this.txtJSON.Text,fileName);
                switch(this.infoRoadAction.Text.ToLower())
                {
                    case "changeview":
                        {
                            this.ViewName = this.infoRoadParameters.Text;
                            this.infoRoadFile.CurrentView = this.ViewName;
                            break;
                        }
                    case "submit":
                        {

                            SaveOrSaveNew(fileName, SaveLocation);
                            // Do some redirect
                            break;
                        }
                    case "cancel":
                        {
                            SPUtility.Redirect(SPContext.Current.Web.Url, SPRedirectFlags.Default, HttpContext.Current);
                            break;
                        }
                    case "saveclose":
                        {
                            SaveOrSaveNew(fileName, SaveLocation);
                            SPUtility.Redirect(SPContext.Current.Web.Url, SPRedirectFlags.Default, HttpContext.Current);
                            break;
                        }
                    case "save":
                        {
                            this.ViewName = this.infoRoadParameters.Text;
                            this.infoRoadFile.CurrentView = this.ViewName;
                            SaveOrSaveNew(fileName, SaveLocation);
                            break;
                        }
                }
            }
            else
            {
                // New file is loading
                if (!string.IsNullOrEmpty(fileName))
                {
                    this.infoRoadFile = new InfoRoadFile();
                    this.infoRoadFile.Read(fileName);
                }

                if (!string.IsNullOrEmpty(templatePath))
                {
                    this.infoRoadFile = new InfoRoadFile();
                    this.infoRoadFile.Create(templatePath);
                }
            }

            if (this.infoRoadFile != null)
            {

                InfoRoadFormView view = this.infoRoadFile.GetView(this.ViewName);
                this.ApplyView(view);
                this.AddValidation(view);
                this.CreateViewButtons(view.name);
                this.AddSaveSubmit();
                this.AddStyles();
                this.txtJSON.Text = this.infoRoadFile.Json;
                Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "ConfirmSubmit", "return mypresubmit();");

            }
            else
            {
                this.lblError.Text = "Ingen mall och inte formulär angivet.";
                this.dropViewList.Visible = false;
                this.txtJSON.Visible = false;
            }
            
        }

       

        

        private void AddValidation(InfoRoadFormView view)
        {
            if (string.IsNullOrEmpty(view.validation))
            {
                string viewValidationUrl = this.infoRoadFile.web.Url + "/_layouts/Dunite.InfoRoad/Script/DefaultValidation.js";
                Page.ClientScript.RegisterClientScriptInclude("DuniteValdation", viewValidationUrl);
            }
            else
            {
                string viewValidationUrl = this.infoRoadFile.web.Url + "/Forms/" + this.infoRoadFile.FormTemplateFolder + "/" + view.validation;
                Page.ClientScript.RegisterClientScriptInclude("DuniteValdation", viewValidationUrl);
            }
        }

        private void SaveOrSaveNew(string fileName, string SaveLocation)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                this.infoRoadFile.SaveNew(SaveLocation);
            }
            else
            {
                this.infoRoadFile.Update();
            }
        }

        private void ApplyView(InfoRoadFormView view)
        {
            
            // Add ViewModel
            string viewModelUrl = this.infoRoadFile.web.Url + "/Forms/" + this.infoRoadFile.FormTemplateFolder + "/" + view.viewmodel;
            Page.ClientScript.RegisterClientScriptInclude("DuniteViewModel", viewModelUrl);
            // http://dev11/sites/test/Forms/BuildPermit/BuildPermit0.Rule.js
            // BuildPermit0.Rule.js
            // Add View
            string viewHTML = this.infoRoadFile.web.GetFileAsString("Forms/" + this.infoRoadFile.FormTemplateFolder + "/" + view.path);
            int bodyStart = viewHTML.IndexOf("<body>");
            int bodeEnd = viewHTML.IndexOf("</body>");
            this.lblForm.Text = viewHTML.Substring(bodyStart + 6, bodeEnd - bodyStart - 6);

            
        }
        private void AddSaveSubmit()
        {
            //<button id="saveButton" type="button" class="dunite-actionButton dunite-Save" onclick="handlepage.prototype.SaveForm();">
            //        Spara
            //</button>
            //<button id="sendButton" type="submit"  class="dunite-actionButton dunite-Submit" onclick="handlepage.prototype.SuperMitForm();" >
            //        Skicka
            //</button>
            InfoRoadFormView view = this.infoRoadFile.GetView( this.infoRoadFile.CurrentView);
            if(view.showsaveSpecified && view.showsave)
            {
                HtmlButton saveBtn = new HtmlButton();
                saveBtn.ID = "saveButton";
                saveBtn.Attributes.Add("class", "dunite-actionButton dunite-Save");
                saveBtn.Attributes.Add("onclick", "handlepage.prototype.SaveForm();");
                saveBtn.Attributes.Add("type", "button");
                saveBtn.InnerText = "Save";
                this.dynamicControlButtons.Controls.Add(saveBtn);
            }
            if (view.showsubmitSpecified && view.showsubmit)
            {
                HtmlButton submitBtn = new HtmlButton();
                submitBtn.ID = "sendButton";
                submitBtn.Attributes.Add("class", "dunite-actionButton dunite-Submit");
                submitBtn.Attributes.Add("onclick", "handlepage.prototype.SuperMitForm();");
                submitBtn.Attributes.Add("type", "button");
                submitBtn.InnerText = "Skicka";
                this.dynamicControlButtons.Controls.Add(submitBtn);
            }
            
        }
        // Move to WebPArt
        private void CreateViewButtons(string viewName)
        {
            /*
             * <div id="radio">
                <input type="radio" id="radio1" name="radio" /><label for="radio1">Choice 1</label>
                <input type="radio" id="radio2" name="radio" checked="checked" /><label for="radio2">Choice 2</label>
                <input type="radio" id="radio3" name="radio" /><label for="radio3">Choice 3</label>
              </div>*/
            int i = 1;
            foreach (InfoRoadFormView view in this.infoRoadFile.infoRoadForm.Views)
            {
                //RadioButton btn = new RadioButton();
                
                HtmlInputRadioButton btn = new HtmlInputRadioButton();
                btn.ID =  "view" + view.name;
                //btn.GroupName = "ViewButtons";
                btn.Name = "ViewButtons"; // "view" + view.name;

                //Literal label = new Literal();
                Label label = new Label();
                label.ID = "LabelView" + view.name;
                //label.Text = string.Format("<label for=\"{1}.{2}</label>",btn.ClientID,i,view.name);
                label.Text = string.Format("{0}.{1}", i, view.name);
                label.AssociatedControlID = btn.ClientID;
                //btn.ClientIDMode = System.Web.UI.ClientIDMode.Static;
                //btn.InnerText = string.Format("{0}.{1}", i,view.name);    

                btn.Attributes.Add("onclick", "javascript:handlepage.prototype.ChangeView('" + view.name + "')");
                btn.Attributes.Add("class", "dunite-actionButton");

                if (viewName == view.name)
                {
                    btn.Checked = true;
                    //btn.Attributes.Add("class", "dunite-actionButton dunite-form-activeview");

                }
                //else
                //{
                //    btn.Attributes.Add("class", "dunite-actionButton");
                //}
                this.viewButtons.Controls.Add(btn);
                this.viewButtons.Controls.Add(label);
                this.dropViewList.Visible = false;
                //if (!this.Page.IsPostBack)
                //{
                //    this.dropViewList.Items.Add(new ListItem(view.name, view.path));
                //}
                i++;
            }
        }

        // Move to WebPArt
        private void AddStyles()
        {
            foreach (var s in this.infoRoadFile.infoRoadForm.Styles)
            {
                HtmlLink css = new HtmlLink();
                
                css.Href = SPContext.Current.Web.Url + "/Forms/" + this.infoRoadFile.FormTemplateFolder + "/" + s.path;
                css.Attributes["rel"] = "stylesheet";
                css.Attributes["type"] = "text/css";
                css.Attributes["media"] = "all";
                Page.Header.Controls.Add(css);
            }
        }

    }
}
